package com.hp.snap.gr.action.impl;

import java.io.File;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.jaxb.ActionType;
import com.hp.snap.gr.model.jaxb.GeneralActionType;
import com.hp.snap.gr.model.jaxb.ParameterType;
import com.hp.snap.gr.utils.CmdResult;
import com.hp.snap.gr.utils.CmdUtils;
import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.Utils;

public class GetLocalGRStatusActionHandler extends AbstractActionHandler {

    private final static String GR_STATUS_FILE_PREFIX = ".SNAP-GR-Status.";
    private static Logger logger = LoggerFactory.getLogger(GetSGMStatusActionHandler.class);

    @Override
    public void execute(ActionType action, Map<String, Object> actionPlanInputs, Map<String, Object> actionPlanOutputs)
            throws ActionException {

        GeneralActionType actionType = (GeneralActionType) action;
        List<ParameterType> parameterTypes = actionType.getParameter();
        Map<String, String> parameterMap = Utils.contructParamMap(parameterTypes);

        String _grStatusFilePath = Constants.USER_HOME + File.separator + "GR";
        CmdResult result = new CmdResult();
        try {

            int rs = CmdUtils.runShellScript("ls -alt " + _grStatusFilePath, result, false);

            if (rs != 0) {
                throw new ActionException("command executed exit code is " + rs);
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new ActionException(ex);
        }
        String resultStr = result.getStdout().toString();
        if (logger.isDebugEnabled()) {
            logger.debug("getting the command result is:{}", resultStr);
        }
        String stats = "NONE";
        try {
            LineNumberReader r = new LineNumberReader(new StringReader(resultStr));
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                int index = line.indexOf(GR_STATUS_FILE_PREFIX);
                if (index >= 0) {
                    String filename = line.substring(index);
                    stats = filename.replace(GR_STATUS_FILE_PREFIX, "").toUpperCase();
                    break;
                }
            }
        } catch (IOException e) {
            throw new ActionException("read the local GR status failed!", e.getCause());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("getting the local GR is:{}", stats);
        }
        actionPlanOutputs.put(Constants.STATUS_LOCAL_SGM, stats);

    }

}
